package TCPDemo;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

/**
 * Tcp版本的 "客户端"
 *
 *ServerSocket: 给 "服务器" 用的,用来监听端口
 *Socket: 给 "服务器" && "客户端" 用的, 用来接收数据
 */
public class TcpEchoClient {
    private Socket socket = null;

    public TcpEchoClient(String serverIp,int serverPort) throws IOException {
        socket = new Socket(serverIp,serverPort);
    }

    public void start(){
        System.out.println("客户端启动!");
        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()){
            while(true){
                //1.从控制台发 构造一个请求
                System.out.print("> ");
                Scanner scanner = new Scanner(System.in);
                String request = scanner.next();

                //2.将请求发送给服务器
                PrintWriter printWriter = new PrintWriter(outputStream);
                printWriter.println(request);
                printWriter.flush();
                //3.从服务器中读取响应
                Scanner respScanner = new Scanner(inputStream);
                String response = respScanner.next();

                //4.把响应显示到界面上
                System.out.println(response);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) throws IOException {
        TcpEchoClient client = new TcpEchoClient("127.0.0.1",6666);
        client.start();
    }
}
